<?php

class AjaxDataController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        // action body
    }

    public function allBlogPostsAction() {
        $this->_helper->Layout->disableLayout();
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $limit = $this->_request->getParam('limit');
        $offset = $this->_request->getParam('start');
        $search_term = $this->_request->getParam('query');
        $language = $this->_request->getParam('language');

        $query = $db->select()
                        ->from('blog_post_info', array(new Zend_Db_Expr('SQL_CALC_FOUND_ROWS post_id AS id'), 'posted_time', 'blog_post_summery', 'blog_post_title', 'blog_post_url'))
                        ->joinLeft('blog_info', "blog_info.blog_id=blog_post_info.blog_id", array('blog_name', 'blog_url', 'language'))
                        ->order('posted_time DESC')
//                        ->where('blog_info.status = ?', 'approved')
//                        ->Where('blog_info.status = ?', 'problematic')
                        ->where('posted_time >= SUBDATE(now(), interval 1 month)');
        if ($language == 'si' || $language == 'ta' || $$language == 'en') {
            $query->where('blog_info.language = ?', $language);
        }
        if (!empty($search_term)) {
            $query->Where("blog_name LIKE ? OR blog_post_summery LIKE ? OR author LIKE ? OR blog_post_title LIKE ? ", "%" . $search_term . "%");
//            $query->orWhere("blog_post_summery LIKE ? ", "%" . $search_term . "%");
//            $query->orWhere("author LIKE ? ", "%" . $search_term . "%");
        }


//        $count = count($db->fetchAll($query));
        if (!empty($limit)) {
            $query->limit($limit, $offset);
        }

        $result = $db->fetchAll($query);
        $count = $db->fetchOne('SELECT FOUND_ROWS()');
        $this->_helper->json(array('data' => $result, 'total' => $count, 'success' => true));
    }

    public function getBlogListAction() {
        $this->_helper->Layout->disableLayout();
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $limit = $this->_request->getParam('limit');
        $offset = $this->_request->getParam('start');
        $type = $this->_request->getParam('type');
        $search_term = $this->_request->getParam('query');
        $query = $db->select()
                        ->from('blog_info', array(new Zend_Db_Expr('SQL_CALC_FOUND_ROWS blog_id AS id'), 'blog_name', 'blog_url'))
                        ->order('blog_name ASC');
        if (!empty($type) && empty($search_term)) {
            $query->where("status= ? ", $type);
        } elseif (!empty($type) && !empty($search_term)) {
            $temp = $db->quoteInto("status = ? ", $type);
            $query->where($temp . " AND blog_name LIKE ? ", "%" . $search_term . "%");
        }
//        $count = count($db->fetchAll($query));
        if (!empty($limit)) {
            $query->limit($limit, $offset);
        }

        $result = $db->fetchAll($query);
        $count = $db->fetchOne('SELECT FOUND_ROWS()');
        $this->getResponse()
                ->setHeader("Content-type", "text/html; charset=utf-8");
        $this->_helper->json(array('data' => $result, 'total' => $count, 'success' => true));
    }

    public function addNewBlogAction() {
        $this->_helper->Layout->disableLayout();
        $status = false;
        $message = "required data missing";
        $data = $_POST;
        $data['status'] = 'new';
        unset($data['agree']);
        if (!empty($_POST['blog_url']) && !empty($_POST['feed_url']) && !empty($_POST['blog_name']) && !empty($_POST['author_name']) && !empty($_POST['author_email']) && !empty($_POST['agree'])) {
            $feedDbvalidator = new Zend_Validate_Db_NoRecordExists(
                            array(
                                'table' => 'blog_info',
                                'field' => 'feed_url'
                            )
            );
            $linkDbValidator = new Zend_Validate_Db_NoRecordExists(
                            array(
                                'table' => 'blog_info',
                                'field' => 'blog_url'
                            )
            );
            $URLvalidator = new Zend_Validate_Callback(array('Zend_Uri', 'check'));
            $Emailvalidator = new Zend_Validate_EmailAddress();
            $Emailvalidator->setOptions(array('domain' => false));
            if (!$URLvalidator->isValid($_POST['blog_url'])) {
                $message = "invalid blog url";
            } elseif (!$linkDbValidator->isValid($_POST['blog_url'])) {
                $message = "blog url " . $_POST['blog_url'] . " already exists in hathmaluwa";
            } elseif (!$URLvalidator->isValid($_POST['feed_url'])) {
                $message = "invalid feed url";
            } elseif (!$feedDbvalidator->isValid($_POST['feed_url'])) {
                $message = "blog url " . $_POST['blog_url'] . " already exists in hathmaluwa";
            } elseif (!$Emailvalidator->isValid($_POST['author_email'])) {
                $message = "invalid email address";
            } elseif (empty($_POST['language'])) {
                $message = "Please select a language";
            } else {
                $status = true;
                $message = "Your Blog Added successfully. Updates from your blog will appear after admin approval";
                $Blog_infoDB = new Application_Model_DbTable_BlogInfo();
                $Blog_infoDB->insert($data);
            }
        }
        $this->_helper->json(array('success' => $status, 'message' => $message));
    }

    public function listWidgetsAction() {
        $this->_helper->Layout->disableLayout();
        $server_name = "http://" . $_SERVER['SERVER_NAME'];
        $imagesArray = array('images' => array(
                array('id' => 1, 'url' => '/badges/join-hathmaluwa.png', 'size' => 'size', 'code' => $server_name),
                array('id' => 2, 'url' => '/badges/en_hathmaluwa2.png', 'size' => 'size', 'code' => $server_name),
                array('id' => 3, 'url' => '/images/hathmaluwa_ext_logo.png', 'size' => 'size', 'code' => $server_name),
                array('id' => 4, 'url' => '/images/join-hathmaluwa.png', 'size' => 'size', 'code' => $server_name),
                array('id' => 5, 'url' => '/images/logo.png', 'size' => 'size', 'code' => $server_name),
                array('id' => 6, 'url' => '/images/hathmaluwa_logo_with_text.gif', 'size' => 'size', 'code' => $server_name),
                array('id' => 7, 'url' => '/badges/si_join_hathmaluwa1.gif', 'size' => 'size', 'code' => $server_name)
                ));
        $this->_helper->json($imagesArray);
    }

        public function allMobilePostsAction() {
        $this->_helper->Layout->disableLayout();
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $limit = $this->_request->getParam('limit');
        $offset = $this->_request->getParam('start');
        $search_term = $this->_request->getParam('query');
        $language = $this->_request->getParam('language');

        $query = $db->select()
                        ->from('blog_post_info', array(new Zend_Db_Expr('SQL_CALC_FOUND_ROWS post_id AS id'), 'posted_time', 'blog_post_summery', 'blog_post_title', 'blog_post_url'))
                        ->joinLeft('blog_info', "blog_info.blog_id=blog_post_info.blog_id", array('blog_name', 'blog_url', 'language'))
                        ->order('posted_time DESC')
//                        ->where('blog_info.status = ?', 'approved')
//                        ->Where('blog_info.status = ?', 'problematic')
                        ->where('posted_time >= SUBDATE(now(), interval 1 month)');
        if ($language == 'si' || $language == 'ta' || $$language == 'en') {
            $query->where('blog_info.language = ?', $language);
        }
        if (!empty($search_term)) {
            $query->Where("blog_name LIKE ? OR blog_post_summery LIKE ? OR author LIKE ? OR blog_post_title LIKE ? ", "%" . $search_term . "%");
//            $query->orWhere("blog_post_summery LIKE ? ", "%" . $search_term . "%");
//            $query->orWhere("author LIKE ? ", "%" . $search_term . "%");
        }


//        $count = count($db->fetchAll($query));
        if (!empty($limit)) {
            $query->limit($limit, $offset);
        }

        $result = $db->fetchAll($query);
        $count = $db->fetchOne('SELECT FOUND_ROWS()');
        $this->getResponse()
                ->setHeader("Content-type", "text/html; charset=utf-8");
        echo 'jsonpcallback('.json_encode(array('data' => $result, 'total' => $count, 'success' => true)).')';
     //   $this->_helper->json(array("jsonpcallback"=>array('data' => $result, 'total' => $count, 'success' => true)));
    }

}

